package com.doudizu.shoesonline.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.doudizu.shoesonline.common.UserContext;
import com.doudizu.shoesonline.constant.UserConstant;
import com.doudizu.shoesonline.mapper.OrdersMapper;
import com.doudizu.shoesonline.model.dto.order.OrderDTO;
import com.doudizu.shoesonline.model.dto.order.OrderQuery;
import com.doudizu.shoesonline.model.entity.OrderDetail;
import com.doudizu.shoesonline.model.entity.Orders;
import com.doudizu.shoesonline.model.entity.User;
import com.doudizu.shoesonline.model.vo.OrderDetailTemp;
import com.doudizu.shoesonline.model.vo.OrdersVO;
import com.doudizu.shoesonline.service.*;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
* 
* @description 针对表【orders(订单)】的数据库操作Service实现
* @createDate 2023-07-03 10:14:50
*/
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders>
    implements OrdersService{

    @Resource
    private UserService userService;

    @Resource
    private AddressService addressService;

    @Resource
    private OrderDetailService orderDetailService;

    @Resource
    @Lazy
    private ProductService productService;

    @Resource
    private LinkService linkService;

    public Object getOrdersVOs(OrderQuery orderQuery) {
        Integer pageNum = orderQuery.getPageNum();
        Integer pageSize = orderQuery.getPageSize();
        //TODO 可选分页
        if (pageNum==null || pageSize==null){
            pageNum=1;
            pageSize=5;
        }
        Page<Orders> objectPage = new Page<>(pageNum, pageSize);
        User loginUser = userService.getById(UserContext.getUserId());

        QueryWrapper<Orders> ordersQueryWrapper = new QueryWrapper<>();
        ordersQueryWrapper.eq(orderQuery.getStatus() != null,"status", orderQuery.getStatus());
        ordersQueryWrapper.eq(orderQuery.getId() != null,"id",orderQuery.getId());
        if (UserConstant.DEFAULT_ROLE.equals(loginUser.getRole())) {
            Integer loginUserId = loginUser.getId();
            ordersQueryWrapper.eq("user_id",loginUserId);
        }
        Page<Orders> ordersPage = this.page(objectPage, ordersQueryWrapper);
        List<Orders> records = ordersPage.getRecords();
        List<OrdersVO> ordersVOs = new ArrayList<>(records.size());
        for (int i = 0; i < records.size(); i++) {
            OrdersVO ordersVO = this.transferToVO(records.get(i));
            ordersVOs.add(i,ordersVO);
        }
        Page<OrdersVO> page = new Page<>();
        BeanUtil.copyProperties(ordersPage,page);
        page.setRecords(ordersVOs);
        return page;
    }

    @Override
    @Transactional
    public List<OrderDetail> submit(OrderDTO orderDTO) {
        Orders order = new Orders();
        BeanUtil.copyProperties(orderDTO,order);
        User user = userService.getLoginUser();
        order.setUserId(user.getId());
        order.setStatus(1);
        user.setScore(user.getScore() + 10 * order.getScore());
        userService.updateById(user);
        this.save(order);
        List<OrderDetail> orderDetailList = orderDTO.getOrderDetailList();
        for (OrderDetail orderDetail : orderDetailList) {
            orderDetail.setOrderId(order.getId());
            orderDetailService.save(orderDetail);
        }
        return orderDetailList;

    }

    @Override
    public Object getOrders(Integer pageNum, Integer pageSize,Integer status) {
        if (pageNum==null && pageSize==null){
            pageNum=1;
            pageSize=5;
        }
        User loginUser = userService.getLoginUser();
        String role = loginUser.getRole();
        QueryWrapper<Orders> ordersQueryWrapper = new QueryWrapper<>();
        if (UserConstant.DEFAULT_ROLE.equals(role)) {
            Integer loginUserId = loginUser.getId();
            ordersQueryWrapper.eq(status != null,"status", status);
            ordersQueryWrapper.eq("user_id",loginUserId);
        }
        if (UserConstant.ADMIN_ROLE.equals(role)) {
            ordersQueryWrapper.eq(status != null,"status", status);
        }
        Page<Orders> objectPage = new Page<>(pageNum,pageSize);
        Page<Orders> page = this.page(objectPage,ordersQueryWrapper);
        List<Orders> orders = page.getRecords();
        List<OrdersVO> ordersVOs = new ArrayList<>(orders.size());
        for (int i = 0; i < orders.size(); i++) {
            OrdersVO ordersVO = this.transferToVO(orders.get(i));
            ordersVOs.add(i,ordersVO);
        }
        Page<OrdersVO> ordersVOPage = new Page<>();
        BeanUtil.copyProperties(page,ordersVOPage);
        ordersVOPage.setRecords(ordersVOs);
        return ordersVOPage;
    }

    @Override
    public Object getOrderDetails(String id) {
        Orders orders = this.getById(id);
        return transferToVO(orders);
    }

    /**
     *
     * @param orders
     * @return
     */
    private OrdersVO transferToVO(Orders orders) {
        OrdersVO ordersVO = new OrdersVO();
        BeanUtil.copyProperties(orders,ordersVO);

        ordersVO.setUsername(userService.getById(orders.getUserId()).getUsername());

        ordersVO.setAddress(addressService.getById(orders.getAddressId()).getAddressName());

        QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();

        orderDetailQueryWrapper.eq("order_id",String.valueOf(orders.getId()));

        List<OrderDetail> orderDetailList = orderDetailService.list(orderDetailQueryWrapper);
        List<OrderDetailTemp> tempList = orderDetailList.stream().map(orderDetail -> {
            OrderDetailTemp orderDetailTemp = new OrderDetailTemp();
            BeanUtil.copyProperties(orderDetail, orderDetailTemp);
            orderDetailTemp.setProductName(productService.getById(orderDetail.getProductId()).getProductName());
            orderDetailTemp.setPrice(productService.getById(orderDetail.getProductId()).getPostPrice());
            String ids = productService.getById(orderDetail.getProductId()).getPictureLinkId();
            String[] idArray = ids.split(",");
            List<Integer> list = Arrays.stream(idArray).map(Integer::valueOf).collect(Collectors.toList());
            List<String> urlList = list.stream().map(item -> linkService.getById(item).getUrl()).collect(Collectors.toList());
            orderDetailTemp.setPictureLink(urlList);
            return orderDetailTemp;
        }).collect(Collectors.toList());
        ordersVO.setOrderDetailList(tempList);

        return ordersVO;
    }

}




